"""
@name: studentmanager.py
@auth: zzw
@date: 2022/12/29 12:30
@desc:
"""
import os

from part1 import utils
from part1.myexception import MyException
from part1.studentdo import StudentDO


class StudentManager:
    __instance = None
    __file_path = os.path.join(os.path.dirname(__file__), "students.pkl")

    def __new__(cls, *args, **kwargs):
        raise ImportError("Instance not be allowed")

    @classmethod
    def get_instance(cls):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance

    def add_student(self, _stu_no: StudentDO) -> bool:
        """
        新增学生
        :param _stu_no: 学生对象
        :return:
        """
        data_list: [StudentDO] = utils.read_data(self.__file_path)
        for data in data_list:
            if _stu_no.get_no == data.get_no:
                raise MyException("学员已存在")

        data_list.append(_stu_no)
        return utils.write_data(self.__file_path, data_list)

    def query_student(self, stu_no: str) -> StudentDO:
        """
        根据学号查询学生信息
        :param stu_no: 学号
        :return:
        """
        data_list: [StudentDO] = utils.read_data(self.__file_path)
        for data in data_list:
            if stu_no == data.get_no:
                return data

    def query_all_students(self) -> list[StudentDO]:
        """
        查询所有学生信息
        :return:
        """
        data_list: [StudentDO] = utils.read_data(self.__file_path)
        return data_list

    def del_all_students(self):
        """
        删除所有学生信息
        :return:
        """
        utils.write_data(self.__file_path, [])


if __name__ == '__main__':
    manager = StudentManager.get_instance()
    stu_do = StudentDO('002', '打工人2', '女')
    # manager.add_student(stu_do)
    print(manager.query_all_students()[1])
    print(manager.query_student('001'))
